package springboot.service;

import springboot.Interface.serviceInterface.LoginServiceInterface;
import springboot.domain.LoginResult;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Service;


@Service
public class LoginService implements LoginServiceInterface {
    @Override
    public LoginResult login(String userName, String password) {
        LoginResult loginResult = new LoginResult();
        if (userName == null || userName.isEmpty()) {
            loginResult.setLogin(false);
            loginResult.setResult("用户名为空");
            return loginResult;
        }
        String msg = "";
        // 将用户名和密码封装到UsernamePasswordToken
        UsernamePasswordToken token = new UsernamePasswordToken(userName, password);
        // 获取Subject实例对象
        Subject currentUser = SecurityUtils.getSubject();
        // 认证
        try {
            currentUser.login(token);// 传到UserRealm类中的方法进行认证
            Session session = currentUser.getSession();
            session.setAttribute("username", userName);
            loginResult.setLogin(true);
            return loginResult;
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            msg = "UnknownAccountException -- > " + e.getMessage();
        } catch (IncorrectCredentialsException e) {
            msg = "IncorrectCredentialsException -- > " + e.getMessage();
        } catch (AuthenticationException e) {
            e.printStackTrace();
            msg = "用户验证失败";
        }
        loginResult.setLogin(false);
        loginResult.setResult(msg);
        return loginResult;
    }
    @Override
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        String name = subject.getSession().getAttribute("username").toString();
        subject.logout();
        return name;
    }
}

